import router, { asyncRoutes, constantRoutes } from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar

  NProgress.start()
  // debugger
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
        console.log(store.state.user.userInfo.roles.menus)
        const filterRoutes = asyncRoutes.filter(item => {
          // return true/false
          return store.state.user.userInfo.roles.menus.includes(item.name)
        })
        console.log(filterRoutes)
        store.commit('user/setRoutes', [...constantRoutes, ...filterRoutes])
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
